import 'package:flutter/foundation.dart' show debugPrint;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:merchants/env.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AppConfig {
  static Future<void> init() async {
    await dotenv.load(fileName: ".env");
  }

  static Future<void> saveConfig(
    String baseUrl,
    int port,
    String apiPrefix,
  ) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('baseUrl', baseUrl);
    await prefs.setInt('port', port);
    await prefs.setString('apiPrefix', apiPrefix);
  }

  static Future<String> _prefsOrEnvString(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(key) ?? dotenv.env[key] ?? '';
  }

  static Future<String> getBaseUrl() async {
    // 1) 优先使用编译期注入的 BASE_URL
    if (Env.baseUrl.isNotEmpty) {
      return Env.baseUrl;
    }

    final baseUrl = await _prefsOrEnvString('BASE_URL');
    if (baseUrl.isEmpty) {
      debugPrint('错误：Base URL 未配置，请检查 SharedPreferences 或 .env 文件');
      throw Exception('Base URL 未配置');
    }
    return baseUrl;
  }

  static Future<int> getPort() async {
    final portString = await _prefsOrEnvString('PORT');
    if (portString.isEmpty) {
      debugPrint('错误：端口号未配置，请检查 SharedPreferences 或 .env 文件');
      throw Exception('端口号未配置');
    }
    try {
      return int.parse(portString);
    } catch (e) {
      debugPrint('错误：端口号格式无效 - $portString');
      throw Exception('端口号格式无效');
    }
  }

  static Future<String> getApiPrefix() async {
    return await _prefsOrEnvString('API_PREFIX');
  }

  static Future<String> getFullBaseUrl() async {
    try {
       // 1) 若编译期已给出 fullBaseUrl 则直接返回
       if (Env.fullBaseUrl.isNotEmpty) {
         return Env.fullBaseUrl;
       }

      final baseUrl = await getBaseUrl();
      final apiPrefix = await getApiPrefix();

       final normalizedBase = baseUrl.endsWith('/')
           ? baseUrl.substring(0, baseUrl.length - 1)
           : baseUrl;
       String normalizedPrefix = apiPrefix.trim();
       if (normalizedPrefix.isNotEmpty && !normalizedPrefix.startsWith('/')) {
         normalizedPrefix = '/$normalizedPrefix';
       }
       return '$normalizedBase$normalizedPrefix';
    } catch (e) {
      debugPrint('错误：无法生成完整 URL - $e');
      rethrow; // 将异常抛出给调用方处理
    }
  }

  static Future<String> getAppVersion() async {
    try {
      final packageInfo = await PackageInfo.fromPlatform();
      return packageInfo.version;
    } catch (e) {
      debugPrint('错误：无法获取应用版本 - $e');
      return 'unknown'; // 默认值
    }
  }
}
